from django.test import TestCase
from database.log import LogConnection
from database import log_conn

import json
from datetime import datetime, timedelta
import os

class LogConnectionTestCase(TestCase):
    def test_parse_time(self):
        pass

    def test_LogConnection_init(self):
        right_config = {
            "url": "https://1.92.152.201:9200",
            "username": "elastic",
            "password": "elastic"
        }
        error_config = {
            "url": "https://1.92.152.201:9200",
            "username": "elastic",
        }
        # 正确连接
        self.assertIsNotNone(LogConnection(right_config).connection)
        # 错误连接
        with self.assertRaises(Exception):
            log_conn2 = LogConnection(error_config)
    
    def test_LogConnection_scroll_query(self):
        query = {
            "query": {
                "bool": {
                    "must": [
                        {"range": {"@timestamp": {"gte": 1716048000.0, "lte": 1716048600.0}}}
                    ]
                }
            },
            "sort": {"@timestamp": {"order": "asc"}},
            "size": 7500,
        }

        indices = ["indice1", "indice2", "indice3"]
        # result = {}
        # self.assertEqual(log_conn.scroll_query(query, indices), result)
    
    def test_LogConnection_query(self):
        node = "node1"
        pod = "pod1"
        start_time = 1716048000.0
        end_time = 1716048600.0

        # result = {}
        # self.assertEqual(log_conn.query(node, pod, start_time, end_time), result)
    
    def test_LogConnection_data_search(self):
        key = "key1"
        value = "value1"

        # result = {}
        # self.assertEqual(log_conn.data_search(key, value), result)
    
    def test_LogConnection_full_text_search(self):
        value = "value1"

        # result = {}
        # self.assertEqual(log_conn.full_text_search(value), result)
    
    def test_LogConnection_export_logs(self):
        start_time = 1716048000.0
        end_time = 1716048600.0

        # result = {}
        # self.assertEqual(log_conn.export_logs(start_time, end_time), result)
    
    def test_LogConnection_message_extract(self):
        # "severity" in data.keys():
        data1 = {
            "severity": "severity",
            "message": "message"
        }
        result1 = "severity:severity,message:message"
        self.assertEqual(log_conn.message_extract(json.dumps(data1)), result1)

        # "level" in data.keys():
        data2 = {
            "level": "level",
            "message": "message"
        }
        result1 = "level:level,message:message"
        self.assertEqual(log_conn.message_extract(json.dumps(data2)), result1)

        # else Exception
        data3 = {
            "message": "message"
        }
        self.assertIsNone(log_conn.message_extract(json.dumps(data3)))
    
    def test_LogConnection_format(self):
        # cmdb_id in self.config["pods"]
        data = [
            {
                "_id": "first",
                "_source": {
                    "kubernetes": {"labels": {"app": "cartservice"}},
                    "@timestamp": datetime(2024, 5, 19, 0, 0, 0),
                    "message": json.dumps({
                        "level": "level",
                        "message": "message"
                    })
                }
            }
        ]
        with open("./api/tests/log.json", "r") as f:
            result = json.load(f)["format"]
        
        self.assertEqual(log_conn.format(data).to_json(), result)

        # cmdb_id not in self.config["pods"]
        result = ['log_id', 'timestamp', 'date', 'cmdb_id', 'message']
        data[0]["_source"]["kubernetes"]["labels"]["app"] = "app_label"
        self.assertEqual(list(log_conn.format(data)), result)

    def test_LogConnection_filter_by_pods(self):
        # cmdb_id in self.config["pods"]
        data = [
            {
                "_source": {
                    "kubernetes": {"labels": {"app": "cartservice"}}
                }
            }
        ]
        self.assertEqual(log_conn.filter_by_pods(data), data)

        # cmdb_id not in self.config["pods"]
        data[0]["_source"]["kubernetes"]["labels"]["app"] = "app_label"
        self.assertEqual(log_conn.filter_by_pods(data), [])
    
    def test_LogConnection_choose_index_template(self):
        start_time = 1716048000.0
        end_time = 1716048600.0

        # result = {}
        # self.assertEqual(log_conn.choose_index_template(start_time, end_time), result)

